package com.cml.infrastructure;

import com.cml.domain.entity.ServerNode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 姓名：陈茂林
 * 时间：2023/10/7 15:23
 * 描述：
 */
public class RemoteServerNodeManager {
    private Map<Integer, ServerNode> remoteServerNodeList = new ConcurrentHashMap();

    public void addRemoteServerNode(ServerNode remoteServerNode){
        this.remoteServerNodeList.put(remoteServerNode.getId(),remoteServerNode);
    }

    public void removeRemoteServerNode(ServerNode remoteServerNode){
        this.remoteServerNodeList.remove(remoteServerNode.getId());
    }

    public ServerNode getServerNode(Integer nodeId){
        return remoteServerNodeList.get(nodeId);
    }

    public Map getAllRemoteServerNode(){
        return remoteServerNodeList;
    }

    public  List<ServerNode> getAllFollowerServerNode() {
        List<ServerNode> allFollowerServerNode = new ArrayList<>();
        Map allRemoteServerNode=this.getAllRemoteServerNode();
        Collection<ServerNode> allRemoteServerNodeList=  allRemoteServerNode.values();
        for(ServerNode remoteServerNode : allRemoteServerNodeList){
            if(remoteServerNode.isFollower()){
                allFollowerServerNode.add(remoteServerNode);
            }
        }
        return allFollowerServerNode;
    }

    public ServerNode getLeaderServerNode(){
        Map allRemoteServerNode=this.getAllRemoteServerNode();
        Collection<ServerNode> allRemoteServerNodeList=  allRemoteServerNode.values();
        for(ServerNode remoteServerNode : allRemoteServerNodeList){
            if(remoteServerNode.isLeader()){
                return remoteServerNode;
            }
        }
        return null;
    }


}
